package com.ns.scs.xf.listener;

import com.google.gson.Gson;
import com.ns.basic.log.utils.LogUtil;
import com.ns.scs.xf.dto.XfDto;
import com.ns.scs.xf.model.JsonParse;
import com.ns.scs.xf.model.Payload;
import com.ns.scs.xf.model.ResHeader;
import com.ns.scs.xf.model.Text;
import com.ns.scs.xf.utils.XFSmsUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * socket listener
 *
 * @author liaowei
 */
@Slf4j
public class XFSocketListener extends WebSocketListener {
    /**
     * 转换
     */
    private static final Gson GSON = new Gson();

    /**
     * 大模型的答案汇总
     */
    private final StringBuilder totalAnswer = new StringBuilder();

    /**
     * 对话历史存储集合
     */
    private static List<Text> histories;
    /**
     * 个性化参数
     */
    private static XfDto listener;

    /**
     * 构造函数
     *
     * @param listener  参数
     * @param histories 历史记录
     */
    public XFSocketListener(XfDto listener, List<Text> histories) {
        XFSocketListener.listener = listener;
        XFSocketListener.histories = histories;
    }

    @Override
    public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {
        super.onOpen(webSocket, response);
        XFSmsUtil.sendMsg(webSocket, listener, histories);
    }

    /**
     * 接收数据
     *
     * @param webSocket socket 参数
     * @param text      响应数据
     */
    @Override
    public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
        JsonParse myJsonParse = GSON.fromJson(text, JsonParse.class);
        Payload payload = myJsonParse.getPayload();
        ResHeader resHeader = myJsonParse.getHeader();
        getResPayLoad(payload);
        if (resHeader.getStatus() == 2) {
            webSocket.close(1000, "结束");
        }
    }

    /**
     * 解析数据
     *
     * @param payload
     */
    private void getResPayLoad(Payload payload) {
        List<Text> textList = payload.getChoices().getText();
        for (Text temp : textList) {
            LogUtil.info(temp.getContent());
            totalAnswer.append(temp.getContent());
            if (!canAddHistory()) {
                histories.remove(0);
            }
            temp.setContent(totalAnswer.toString());
            histories.add(temp);
        }
    }

    /**
     * 由于历史记录最大上线1.2W左右，需要判断是能能加入历史
     *
     * @return boolean
     */
    public boolean canAddHistory() {
        int historyLength = 0;
        for (Text temp : histories) {
            historyLength = historyLength + temp.getContent().length();
        }
        return historyLength <= listener.getMaxTokens();
    }

    @Override
    public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, Response response) {
        try {
            super.onFailure(webSocket, t, response);
            if (null != response) {
                log.error("讯飞模型错误，错误码{}，错误原因如下：{}", response.code(), response.body());
            }
        } catch (Exception e) {
            log.error("讯飞模型错误，错误信息如下:{}", e.getMessage());
        } finally {
            webSocket.close(1000, "");
        }
    }
}
